package com.tanhua.dubbo.server.api;


import com.alibaba.dubbo.config.annotation.Service;
import com.tanhua.dubbo.server.pojo.RecommendUser;
import com.tanhua.dubbo.server.vo.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

/**
 * @Author: JinboYang
 * @Description:
 * @Date: Created in 18:27 2021/1/4
 * @ModifiedBy:
 */

@Service(version = "1.0.0")
public class RecommendUserApiImpl implements RecommendUserApi {

    //注入mongodb
    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * @Description: 实现业务查询缘分值最高的用户
     * @Param:[userId]
     * @return:com.tanhua.dubbo.server.pojo.RecommendUser
     * @Author:JinboYang
     * @Date:2021/1/4
     */
    @Override
    public RecommendUser queryWithMaxScore(Long userId) {
        Query query = Query.query(Criteria.where("toUserId").is(userId)).with(Sort.by(Sort.Order.desc("score"))).limit(1);
        return mongoTemplate.findOne(query, RecommendUser.class);
    }

    /**
     * @Description: 业务实现 倒序
     * @Param:[userId, pageNum, pageSize]
     * @return:com.tanhua.dubbo.server.vo.PageInfo<com.tanhua.dubbo.server.pojo.RecommendUser>
     * @Author:JinboYang
     * @Date:2021/1/4
     */
    @Override
    public PageInfo<RecommendUser> queryPageInfo(Long userId, Integer pageNum, Integer pageSize) {
        //先进行分页
        PageRequest pageRequest = PageRequest.of(pageNum - 1, pageSize, Sort.by(Sort.Order.desc("score")));
        //查询到最高分然后倒序
        Query query = Query.query(Criteria.where("toUserId").is(userId)).with(pageRequest);
        List<RecommendUser> recommendUserList = mongoTemplate.find(query, RecommendUser.class);
        //暂时不提供总数
        return new PageInfo<>(0, pageNum, pageSize, recommendUserList);
    }

    /**
       * @Description: 查询好友缘分值
       * @Param:[userId, toUserId]
       * @return:double
       * @Author:JinboYang
       * @Date:2021/1/13
       */
    @Override
    public double queryScore(Long userId, Long toUserId) {
        Query query = Query.query(Criteria
                .where("toUserId").is(toUserId)
                .and("userId").is(userId));
        RecommendUser recommendUser = this.mongoTemplate.findOne(query, RecommendUser.class);
        if (null == recommendUser) {
            return 0;
        }
        return recommendUser.getScore();
    }
}
